using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace XsltTask
  {
  public class Xslt : Task
    {
    private string xsltFile;

    private string sourceXmlFile;

    private string targetXmlFile;

    [Required]
    public string XsltFile
    {
      get { return xsltFile; }
      set { xsltFile = value; }
    }

    [Required]
    public string SourceXmlFile
    {
      get { return sourceXmlFile; }
      set { sourceXmlFile = value; }
    }

    [Required]
    public string TargetXmlFile
    {
      get { return targetXmlFile; }
      set { targetXmlFile = value; }
    }

    public override bool Execute()
    {
      bool result = true;

      Log.LogMessage("Transforming from {0} to {1} using {2}",
      SourceXmlFile, TargetXmlFile, XsltFile);

      try
      {
        XslCompiledTransform xslTransform = GetXslTransform(XsltFile);
        XmlReader xmlReader = GetXmlReader(SourceXmlFile);
        XmlWriter xmlWriter = GetXmlWriter(TargetXmlFile);
        xslTransform.Transform(xmlReader, xmlWriter);
      }
      catch (Exception e)
      {
        Log.LogErrorFromException(e);
        result = false;
      }

      return result;
    }

    XslCompiledTransform GetXslTransform(String file)
    {
      XslCompiledTransform xslTransform = new XslCompiledTransform();
      xslTransform.Load(GetXmlReader(file));
      return xslTransform;
    }

    XmlReader GetXmlReader(String file)
    {
      return new XmlTextReader(GetTextReader(file));
    }

    XmlWriter GetXmlWriter(String file)
    {
      TextWriter textWriter = new StreamWriter(file);
      return new XmlTextWriter(textWriter);
    }

    TextReader GetTextReader(String file)
    {
      return new StreamReader(file);
    }
  }
}